package leesoft.gocrm.servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.Template;
import org.apache.velocity.context.Context;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.tools.view.servlet.VelocityLayoutServlet;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

abstract public class LayoutServletBase extends VelocityLayoutServlet {
	public final static String KEY_CURRENT_ACTION="current_action";
	public final static String KEY_CURRENT_USER="current_user";
	public final static String KEY_LOGOUT_URL="log_out_url";
	public void init(ServletConfig config) throws ServletException
	{
		super.init(config);
		//customize the glabal properties
	}
	protected Context createContext(HttpServletRequest request,
            HttpServletResponse response)
	{

		Context ctx = super.createContext(request, response);
		String currentAction=getCurrentAction();
		if(currentAction!=null)
			ctx.put(KEY_CURRENT_ACTION, currentAction);
		String currentLayout=getCurrentLayout();
		if(currentLayout!=null)
			ctx.put(KEY_LAYOUT, currentLayout);
		UserService userService = UserServiceFactory.getUserService();
		ctx.put(KEY_CURRENT_USER, userService.getCurrentUser().getEmail());
		ctx.put(KEY_LOGOUT_URL, userService.createLogoutURL("/"));	
		return ctx;
	}
	protected void fillContext(Context context, HttpServletRequest request)
    {
        // this implementation does nothing
    }
	protected Template getTemplate(HttpServletRequest request,
            HttpServletResponse response)throws ResourceNotFoundException, ParseErrorException, Exception
	{
		String path = createTemplatePath();
		if (response == null)
		{
			return getTemplate(path);
		}
		else
		{
			return getTemplate(path, response.getCharacterEncoding());
		}
	}
	abstract protected String createTemplatePath();
	abstract protected String getCurrentAction();
	//this could be overrided by any child class
	protected String getCurrentLayout()
	{
		return null;
	}
}
